<template>
  <div class="ChatRoom">
      <!-- 导航栏 -->
      <nav-bar class="navbar">
          <div slot="left" class="backButton" @click="back"><img src="@/assets/img/message/backButton.svg" alt=""></div>
          <div slot="center" class="name"><h2>{{ activeFriendData.userName }}</h2></div>
          <div class="more" slot="right">...</div>
      </nav-bar>
      <!-- 聊天框 -->
      <scroll class="content">
        <div class="chat">
            <div v-for='(item, index) in RecordChat' :key="index">
                <record-item :item='item' :myId='userId'></record-item>
            </div>
        </div>
      </scroll>
      <!-- 底部发送消息栏 -->
      <nav-bar class="chatBottom">
          <div slot="left" class="voice"><img src="@/assets/img/message/语音.svg" alt=""></div>
          <input 
            ref="sendMessage" 
            type="text" 
            class="sendMessage" 
            slot="center" 
            v-on:input="showSend" 
            v-model="contentText"
            @keyup.enter="sendMessage"
            >
          <div class="emoAmor" slot="right"  v-show="show">
              <img class="emo" src="@/assets/img/message/emoticon.svg" alt="">
              <img class="mor" src="@/assets/img/message/more.svg" alt="">
          </div>
          <div class="sendBtn" slot="right" v-show="!show">
              <button @click="sendMessage">发送</button>
          </div>
      </nav-bar>
  </div>
</template>

<script>
  import NavBar from '@/components/common/navbar/NavBar.vue'
  import RecordItem from './RecordItem.vue'
  import Scroll from '@/components/common/scroll/Scroll.vue'
  import { mapMutations, mapState } from 'vuex'
  
  export default {
    name: 'ChatRoom',
    components: { 
        NavBar,
        RecordItem,
        Scroll,
    },
    data() {
        return {
            show: true,
            socket: null,
            contentText: '',
            RecordChat:[],
            showTime: true,
        }
    },
    computed: {
        ...mapState(['activeFriendData','chatRecode'])
    },
    methods: {
        ...mapMutations(['HANDLER_LAST_CHAT_RECODE']),
        back () {
            this.$router.back()
        },
    // 打开聊天室
        initSocket() {
            // console.log('打开websocket了')
            if(typeof(WebSocket) == "undefined") { 
                console.log("您的浏览器不支持WebSocket");
            }else{
                console.log("您的浏览器支持WebSocket");
                //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
                //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
                let socketUrl="http://cves6f.natappfree.cc/imserver/" + this.userId;
                socketUrl=socketUrl.replace("https","ws").replace("http","ws");
                if(this.socket!== null){
                    this.socket.onclose();
                    this.socket=null;
                }
                this.socket = new WebSocket(socketUrl);
                console.log(this.socket);
                //打开事件
                this.socket.onopen = function() {
                    console.log("websocket已打开");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                //获得消息事件
                this.socket.onmessage = (msg) => {
                    if(msg.data!="连接成功"){
                        var json=JSON.parse(msg.data);
                        this.RecordChat.push(json)
                        console.log(this.RecordChat);
                        // this.HANDLER_LAST_CHAT_RECODE(message)
                        console.log("用户2",json);
                    }
                    // console.log(msg.data);
                    //发现消息进入    开始处理前端触发逻辑
                };
                //关闭事件
                this.socket.onclose = function(e) {
                  console.log(e.code + ' ' + e.reason + ' ' + e.wasClean);
                  console.log("websocket已关闭");
                };
                //发生了错误事件
                this.socket.onerror = function(e) {
                    console.log("websocket发生了错误");
                }
            }
        },
        // 发送消息
        sendMessage() {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else {
                console.log("您的浏览器支持WebSocket");
                let message = new Object();
                message.userId = this.userId;
                message.ToUserId = this.activeFriendData.id;
                message.ContentText = this.contentText
                if(message.ContentText.trim() === '') alert('消息不能为空！') //判断是否为空串或纯白消息，是则报错
                else{
                  message.SendTime = this.CurentTime();
                // 判断是否大于三分钟来决定showTime的值，0和大于三分钟为true，三分钟以内为false
                let len = this.RecordChat.length
                if(len == 0){
                    this.showTime = true
                }else if(len == 1){
                    this.showTime = false
                }else{
                    // 转时间戳
                    let nowTime = this.RecordChat[len-1].SendTime;
                    nowTime = nowTime.substring(0,19)
                    nowTime = new Date(nowTime).getTime()
                    let lastTime = this.RecordChat[len-2].SendTime;
                    lastTime = lastTime.substring(0,19)
                    lastTime = new Date(lastTime).getTime()
                    // 时间戳的单位为毫秒，3分钟=180000毫秒
                    if((nowTime - lastTime) >= 0 &&  (nowTime - lastTime) < 180000){
                    this.showTime = false
                    }else{ this.showTime = true }
                } 
                message.showTime = this.showTime
                // 将发送的消息添加到聊天中
                this.RecordChat.push(message)
                this.HANDLER_LAST_CHAT_RECODE(message)
                let json = JSON.stringify(message);
                this.socket.send(json);
                console.log(json);
            }
                }
            this.contentText = ''
            this.show = true
        },
        // 生成发送消息时间
        CurentTime(){
            var now = new Date();
            var year = now.getFullYear();       //年
            var month = now.getMonth() + 1;     //月
            var day = now.getDate();            //日
            var hh = now.getHours();            //时
            var mm = now.getMinutes();          //分
            var ss=now.getSeconds();
            var clock = year + "-";
            if(month < 10)
                clock += "0";
            clock += month + "-";
            if(day < 10)
                clock += "0";
            clock += day + " ";
            if(hh < 10)
                clock += "0";
            clock += hh + ":";
            if (mm < 10) clock += '0';
            clock += mm+":"+ss;
            return(clock);
        },

        // 修改show的值，是否展示发送按钮
        showSend () {
            if(this.$refs.sendMessage.value){
               this.show = false
            } else {
               this.show = true
            }
        }
    },
    mounted() {
        this.userId = JSON.parse(localStorage.user).id
        this.friendData = this.$route.query
        this.initSocket()
    },
    
    watch: {
        contentText( newvalue,oldvalue) {
            let lastTime = this.CurentTime().slice(11,16)
            if(newvalue){
            this.$bus.$emit('lastMessage', {lastMessage:newvalue,lastTime:lastTime})
            }else{
            this.$bus.$emit('lastMessage', {lastMessage:oldvalue,lastTime:lastTime})
            }
        }
    },
  }
</script>

<style scoped>
/* 回退按钮样式 */
.backButton {
    position: relative;
}
.backButton img {
    height: 20px;
    width: 20px;
    display: inline-block;
    vertical-align: middle;
}
/* 设置导航栏样式 */
.navbar {
    border-bottom: 1px solid rgb(245, 244, 244);
}
/* 设置 更多 按钮样式 */
.more {
    font-size: 20px;
    text-align: right;
    padding-right: 10px;
}

/* 设置聊天区样式 */
.content {
    height: calc(100vh - 87px);
    background-color: rgb(245, 245, 245);
    overflow: hidden;
}

/* 设置底部发送消息样式 */
.chatBottom {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    border-top: 1px solid rgb(245, 244, 244);
}
/* 设置语音按钮样式 */
.voice {
    text-align: center;
    padding-left: 10px;
}
.voice img {
    height: 30px;
    display: inline-block;
    vertical-align: middle;
}
/* 设置输入框样式 */
.sendMessage {
    height: 30px;
    width: 100%;
    padding: 5px;
    border-radius: 8px;
    border: 1px solid rgb(230, 228, 228);
    font-size: 18px;
}
/* 设置输入框选中之后的样式 */
.sendMessage:focus {
    outline: none;
    height: 30px;
    width: 100%;
    border-radius: 8px;
    border: 1px solid rgb(138, 137, 137);
}
/* 设置表情和更多按钮样式 */
.emoAmor {
    display: flex;
}
/* 设置表情按钮样式 */
.emo {
    flex: 1;
    height: 40px;
    width: 50%;
}
/* 设置更多按钮样式 */
.mor {
    flex: 1;
    height: 40px;
    width: 50%;
    padding: 2px;
}
/* 设置发送按钮样式 */
.sendBtn button {
    height: 30px;
    width: 70%;
    color: #fff;
    border: none;
    border-radius: 5px;
    background-color: rgb(25, 185, 25);
}
/* 设置好友名字样式 */
.name {
    font-size: 12px;
}
</style>